/*
 * DynamicPie.cpp
 *
 *  Created on: 2013-2-3
 *      Author: Dspark
 */

#include "DynamicPie.h"

DynamicPie::DynamicPie(qreal radius):
SolidPie(radius,0)
{

}
void DynamicPie::addItem(QString name, qreal value)
{
	if(fans.contains(name))
	{
		max += value;
		fans[name]->value += value;
		if(fans[name]->value <=0 )
		{
			fans.remove(name);
		}
	}else{
		max += value;
		PieFan* temp  = new PieFan;
		temp->value = value;
		fans[name] = temp;
	}
	this->update();
}

DynamicPie::~DynamicPie() {
	// TODO Auto-generated destructor stub
}


void DynamicPie::paintEvent(QPaintEvent *event)
{
	QPainter painter(this);
	painter.setRenderHint( QPainter::Antialiasing, true );
	painter.setPen(Qt::NoPen);

	QMapIterator<QString,PieFan*> iter(fans);
	PieFan* fan = 0;
	qreal start = 0;
	while(iter.hasNext())
	{
		iter.next();
		fan = iter.value();
		QBrush brush(fan->color,Qt::SolidPattern);
		painter.setBrush(brush);
		qreal rate = fan->value/this->max;
		qreal span = rate*5760;
		if(rate > 0)
		{
			painter.drawPie(this->pieRect,start, span);


			QPointF p = pieRect.center();
			qreal arc = (start + span/2)/2880*PI;
			painter.setPen(Qt::SolidLine);
			QPointF a(0,0);
			QString text = QString("%1, %2%").arg(iter.key()).arg(rate*100);

			if( (arc > 0 && arc <= PI/2) )
			{
				a.setX( p.x() + radius*std::cos(arc) );
				a.setY( p.y() - radius*std::sin(arc));
			}else if(arc < PI)
			{
				a.setX(  p.x() + radius*std::cos(arc) - painter.fontMetrics().width(text)  );
				a.setY( p.y() - radius*std::sin(arc) );
			}else if( arc < 3*PI/2){
				a.setX(  p.x() + radius*std::cos(arc) - painter.fontMetrics().width(text)  );
				a.setY(  p.y() - radius*std::sin(arc) + painter.fontMetrics().height() );
			}else{
				a.setX(  p.x() + radius*std::cos(arc) );
				a.setY(  p.y() - radius*std::sin(arc) + painter.fontMetrics().height() );
			}
			painter.drawText(a,text);
			/*painter.drawText(
					painter.boundingRect(
							QRectF(a.x(),a.y(),painter.fontMetrics().width(text),painter.fontMetrics().height()),text
					),
					Qt::AlignRight,
					text
			);*/
			painter.setPen(Qt::NoPen);
		}
		start = start + span;


	}
	static const qreal CIRCLE = 360*16;
	if(start < CIRCLE)
	{
		QBrush brush(Qt::darkGray,Qt::Dense3Pattern);
		painter.setBrush(brush);
		painter.drawPie(this->pieRect,start, CIRCLE-start);
	}
}
